import React, { useEffect, useState } from "react";
import {
  DownloadOutlined,
  PhoneOutlined,
  UserOutlined,
  FileDoneOutlined,
  CopyOutlined,
  LeftOutlined,
  UpOutlined,
  CloseOutlined,
  CheckOutlined,
  DownOutlined,
  UploadOutlined,
  AudioOutlined,
  LoadingOutlined,
} from "@ant-design/icons";
import { Table, Button, Modal, Input, message, Spin } from "antd";
import "./index.less";
import { useHistory, useParams } from "react-router-dom";
import { useQuery } from "@/shared/util";
import callNet from "@/servers/callNet";
import { recordStart, pause as pauseFunc, goOn, stop } from "./sendRecord";
import pause from "@/assets/pause.png";
import play from "@/assets/play.png";
import dayjs from "dayjs";
import { marked } from "./marked.js";
import Markdown from "@/components/Markdown.jsx";
import ZoomMtgEmbedded from "@zoom/meetingsdk/embedded";

const recordStatusEnum = {
  init: 0,
  recording: 1,
  pause: 2,
  end: 3,
};

let recordStartTime = null;

export default function App0() {
  const [uploading, setUploading] = useState(false);
  const [loading, setLoading] = useState(false);
  const [showOptions, setShowOptions] = useState(false);
  const [showTranslateText, setShowTranslateText] = useState(false);
  const [translateText, setTranslateText] = useState([]);
  const [messageApi, contextHolder] = message.useMessage();
  const [uploadSuccess, setUploadSuccess] = useState(false);
  let {
    meeting_id,
    customer,
    title,
    meeting_type,
    pageStatus,
    template_id,
    meetingNum,
    meetingPwd,
    meetingName,
  } = useQuery();
  const [customerName, setCustomer] = useState("");
  const [displayTitle, setDisplayTitle] = useState("");
  const [createTime, setCreateTime] = useState("");
  const [OPTIONS_TEMPLATE, setTemplateOptions] = useState([]);
  const [chooseTemplate, setChooseTemplate] = useState({});
  const [generating, setGenerating] = useState(false);
  const [generateNote, setGenerateNote] = useState("");
  const [generateNoteEnd, setGenerateNoteEnd] = useState(false);
  const [myNote, setMyNote] = useState("");
  const [recordStatus, setRecordStatus] = useState(recordStatusEnum.init);
  const now = dayjs().format("YYYY-MM-DD HH:mm:ss");
  const [recordTemplateText, setRecordTemplateText] = useState("");
  let client; //zoom客户端

  // const createTime = c_time || now;

  const [chooseTab, setChooseTab] = useState("0");

  useEffect(() => {
    getTemplateOptions();
    customer && setCustomer(customer);
    if (pageStatus === "detail") {
      getDetails();
    } else {
      setCustomer(customer);
      setCreateTime(now);
      setDisplayTitle(title);
      if (meeting_type === "1") {
        // 加入会议
        joinMeeting();
      }
    }
    return () => {
      if (meeting_type === "2") {
        endRecord();
      }
      if (meeting_type === "1") {
        ZoomMtgEmbedded.destroyClient();
        endRecord();
      }
    };
  }, []);
  const history = useHistory();

  const goBack = () => {
    history.goBack();
  };

  // isSwitch是否换了一个人在说话, t：转换语言的文本
  const getRecordText = (data, templateText) => {
    const filterData = data.filter((e) => e.content);
    // 设置已解析的对话数据
    setTranslateText(filterData);
    // 设置临时对话数据（可能有误）
    setRecordTemplateText(templateText);
  };

  const getDetails = async () => {
    try {
      setLoading(true);
      const { notes } = await callNet.get("/note_details", { meeting_id });
      // title,customer,ctime
      setCustomer(notes?.customer);
      setCreateTime(notes?.ctime);
      setDisplayTitle(notes?.title);
      setMyNote(notes?.note);
      setGenerateNote(notes?.xcontent);
      setGenerateNoteEnd(true);
      setTranslateText(notes?.content);
      setChooseTab("1");
    } catch (err) {
    } finally {
      setLoading(false);
    }
  };

  const startListenZoom = (client) => {
    // 注册事件监听
    client.on("connection-change", (payload) => {
      const {state} = payload
      console.log("*connection-change", payload);
      if (state === "Connected") {
        startRecording();
      }
      if (state === "Closed") {
        endRecord();
      }
    });
  };

  const joinMeeting = async () => {
    // meetingNum, meetingPwd, meetingName
    client = ZoomMtgEmbedded.createClient();
    const authEndpoint = "http://localhost:4000"; // http://localhost:4000
    const role = 0;
    const userEmail = "";
    const registrantToken = "";
    const zakToken = "";
    const { sdkKey, signature } = await callNet.post(authEndpoint, {
      meetingNumber: meetingNum,
      role,
    });
    const meetingSDKElement = document.getElementById("meetingSDKElement");
    await client.init({
      zoomAppRoot: meetingSDKElement,
      language: "en-US",
      patchJsMedia: true,
      leaveOnPageUnload: true,
    });
    startListenZoom(client);
    await client.join({
      signature: signature,
      sdkKey: sdkKey,
      meetingNumber: meetingNum,
      password: meetingPwd,
      userName: meetingName,
      userEmail: userEmail,
      tk: registrantToken,
      zak: zakToken,
    });
  };

  const getTemplateOptions = async () => {
    const { templates } = await callNet.get("/templates");
    const options = templates.map((e) => ({
      label: e.template_name,
      value: e.template_id,
    }));
    if (template_id) {
      const initChoose = options.find((e) => e.value === template_id);
      setChooseTemplate(initChoose);
    }
    setTemplateOptions(options);
  };

  const chooseFile = () =>
    new Promise((resolve, reject) => {
      const input = document.createElement("input");
      input.type = "file";
      input.accept = "audio/*";
      input.onchange = (e) => {
        const file = e.target.files[0];
        console.log("传统方法选择的文件:", file);
        resolve(file);
      };
      input.click();
    });

  const uploadRecordFile = async () => {
    const file = await chooseFile();
    try {
      showMessage.warn("录音文件上传中...");
      setUploading(true);
      const res = await callNet.upload("/lfasr_transcribe", file, {
        meeting_id,
      });
      showMessage.ok("录音文件上传成功！");
      setUploadSuccess(true);
    } catch (err) {
      showMessage.error("录音文件上传失败，请稍后再试！");
      setUploadSuccess(false);
    } finally {
      setUploading(false);
    }
  };

  const getTranslateText = async () => {
    try {
      const { result } = await callNet.get("/transcripts", { meeting_id });
      setTranslateText(result);
    } catch (err) {
    } finally {
    }
  };

  const toggleShowTranslate = () => {
    if (
      !showTranslateText &&
      !translateText?.length &&
      pageStatus === "edit" &&
      meeting_type === "3"
    ) {
      getTranslateText();
    }
    setShowTranslateText(!showTranslateText);
  };

  const setChooseTemplateFunc = (option) => {
    setShowOptions(false);
    setChooseTemplate(option);
  };

  const toggleShowOptions = () => {
    setShowOptions(!showOptions);
  };

  const generate = async () => {
    let url, params;
    if (!chooseTemplate || !chooseTemplate.value) {
      showMessage.warn("请选择模板");
      return;
    }
    if (meeting_type === "2") {
      if (!translateText || !translateText.length) {
        showMessage.warn("请先进行录音");
        return;
      }

      url = "/records";
      params = {
        meeting_id,
        voice: translateText ? JSON.stringify(translateText) : "",
        note: myNote,
        template_id: chooseTemplate.value,
      };
    } else {
      // meeting_type==='3'
      // uploadSuccess
      if (!uploadSuccess) {
        showMessage.warn("请上传录音文件");
        return;
      }
      url = "/analyze";
      params = {
        content: myNote,
        cue: "",
        meeting_id,
        template_id: chooseTemplate.value,
      };
    }
    if (generating) return;
    try {
      setGenerating(true);
      const { result } = await callNet.post(url, params);
      showMessage.ok("ai强化笔记已经生成");
      setGenerateNote(result);
      setGenerateNoteEnd(true);
      setChooseTab("1");
    } catch (err) {
    } finally {
      setGenerating(false);
    }
  };

  const chooseTabFunc = (tab) => {
    setChooseTab(tab);
  };

  function copyToClipboard(text) {
    // 现代方法：使用 Clipboard API
    if (navigator.clipboard) {
      return navigator.clipboard
        .writeText(text)
        .then(() => {
          showMessage.ok("已复制ai强化笔记");
          return true;
        })
        .catch(async (err) => {
          // 尝试回退到旧方法
          // console.error('Clipboard API 失败，尝试旧方法:', err);
        });
    } else {
      // 直接使用旧方法
      // return Promise.resolve(fallbackCopyText(text));
    }
  }

  const recordCurrentTime = () => {
    const now = new Date().getTime(); //开始毫秒
    return dayjs(now - recordStartTime - 1000 * 60 * 60 * 8).format("HH:mm:ss");
  };

  // 开始录音
  const startRecording = () => {
    setRecordStatus(recordStatusEnum.recording);
    recordStart(getRecordText);
    recordStartTime = new Date().getTime(); //开始毫秒
  };

  // 暂停录音
  const pauseRecord = () => {
    setRecordTemplateText("");
    setRecordStatus(recordStatusEnum.pause);
    pauseFunc();
  };

  // 继续录音
  const continueRecord = () => {
    setRecordStatus(recordStatusEnum.recording);
    goOn();
  };

  // 结束录音
  const endRecord = () => {
    setRecordTemplateText("");
    setRecordStatus(recordStatusEnum.end);
    stop();
    recordStartTime = null;
  };

  const renderResponse = () => {
    if (chooseTab === "0") {
      return (
        <Input.TextArea
          className="my-note"
          placeholder={
            pageStatus === "detail" ? "未书写笔记..." : "请在此处输入笔记..."
          }
          value={myNote}
          onChange={(e) => setMyNote(e.target.value)}
          readOnly={pageStatus === "detail"}
        ></Input.TextArea>
      );
    } else if (chooseTab === "1") {
      return [
        <div className="note-pro">
          <Markdown>{generateNote}</Markdown>
        </div>,
        <div
          className="copy-button"
          onClick={() => copyToClipboard(generateNote)}
        >
          <CopyOutlined />
          复制AI内容
        </div>,
      ];
    } else if (chooseTab === "2") {
      return (
        <div className="translate-container">
          {translateText?.map((item, index) => {
            return (
              <div key={index}>
                <h3>
                  {item.user} <span className="create-time">{item.time}</span>
                </h3>
                <p>{item.content}</p>
              </div>
            );
          })}
        </div>
      );
    }
  };

  const renderTranslate = () => {
    return (
      <div>
        {translateText?.map((item, index) => {
          return (
            <div key={index}>
              <h3>
                {item.user} <span className="create-time">{item.time}</span>
              </h3>
              <p>{item.content}</p>
            </div>
          );
        })}
        {recordTemplateText && (
          <>
            <h3>
              <AudioOutlined style={{ marginRight: "5px", color: "green" }} />
              正在录音中......
            </h3>
            <p>{recordTemplateText}</p>
          </>
        )}
      </div>
    );
  };

  return (
    <div className="page-container">
      {contextHolder}
      {meeting_type === "1" && pageStatus === "edit" ? (
        <div id="meetingSDKElement"></div>
      ) : null}
      <div className="header">
        <Button onClick={goBack} icon={<LeftOutlined />} type="primary">
          返回
        </Button>
      </div>
      <Spin spinning={loading}>
        <div className="page-content">
          <div className="content-left"></div>
          <div className="content-center">
            <div className="content-header">
              <h1>{displayTitle}</h1>
              <p>
                {createTime}
                <span>
                  <UserOutlined style={{ marginRight: "5px" }} />
                  {customerName}
                </span>
              </p>
            </div>

            <div className="content-container">
              <div className="tabs">
                {generating ? (
                  <div className="loading">
                    <LoadingOutlined /> <span>正在生成中...</span>
                  </div>
                ) : generateNoteEnd ? (
                  <>
                    <div
                      onClick={() => chooseTabFunc("1")}
                      className={chooseTab === "1" ? "tab active" : "tab"}
                    >
                      Ai 强化笔记
                    </div>
                    <div
                      onClick={() => chooseTabFunc("0")}
                      className={chooseTab === "0" ? "tab active" : "tab"}
                    >
                      我的笔记
                    </div>
                    {pageStatus === "detail" && (
                      <div
                        onClick={() => chooseTabFunc("2")}
                        className={chooseTab === "2" ? "tab active" : "tab"}
                      >
                        录音内容
                      </div>
                    )}
                  </>
                ) : null}
              </div>
              <div className="content-view">{renderResponse()}</div>
            </div>
            {pageStatus === "edit" && (
              <div className="content-footer">
                {meeting_type === "3" && (
                  <>
                    {uploadSuccess ? (
                      [
                        <div className="record-detail">
                          <div
                            className="record-detail-button"
                            onClick={toggleShowTranslate}
                          >
                            <span>音频内容</span>
                            {showTranslateText ? (
                              <DownOutlined />
                            ) : (
                              <UpOutlined />
                            )}
                          </div>
                          {showTranslateText && (
                            <div
                              className="translate-content-modal"
                              onClick={() => {}}
                            >
                              <h1>
                                音频文件内容
                                <CloseOutlined onClick={toggleShowTranslate} />
                              </h1>
                              <div>{renderTranslate()}</div>
                            </div>
                          )}
                        </div>,
                        <div className="generate">
                          <div
                            className={
                              generating
                                ? "button-content disabled"
                                : "button-content"
                            }
                            onClick={generate}
                          >
                            {generating
                              ? [
                                  <LoadingOutlined className="generate-loading" />,
                                  "会议纪要生成中",
                                ]
                              : "AI生成会议纪要"}
                          </div>
                          <div className="meeting-type">
                            <div className="choose" onClick={toggleShowOptions}>
                              {chooseTemplate?.label || "请选择"}{" "}
                              {showOptions ? <DownOutlined /> : <UpOutlined />}
                            </div>
                            {showOptions
                              ? OPTIONS_TEMPLATE.map((e) => {
                                  return (
                                    <div
                                      key={e.value}
                                      className="option-item"
                                      onClick={() => setChooseTemplateFunc(e)}
                                    >
                                      {e.label}
                                    </div>
                                  );
                                })
                              : null}
                          </div>
                        </div>,
                      ]
                    ) : (
                      <div
                        className="upload-record-file"
                        onClick={uploadRecordFile}
                      >
                        {!uploading ? <UploadOutlined /> : <LoadingOutlined />}
                      </div>
                    )}
                  </>
                )}

                {meeting_type === "2" && (
                  <>
                    {recordStatus === recordStatusEnum.init && (
                      <div
                        className="start-record"
                        onClick={startRecording}
                      ></div>
                    )}
                    {recordStatus !== recordStatusEnum.init && (
                      <div
                        className={
                          recordStatus === recordStatusEnum.recording
                            ? "record-detail record-detail-recording"
                            : "record-detail"
                        }
                      >
                        <div
                          className="record-detail-button"
                          onClick={toggleShowTranslate}
                        >
                          <span>
                            {recordStatus === recordStatusEnum.recording
                              ? [
                                  <AudioOutlined className="record_icon" />,
                                  "录音中...",
                                ]
                              : "音频内容"}
                          </span>{" "}
                          {showTranslateText ? (
                            <DownOutlined />
                          ) : (
                            <UpOutlined />
                          )}
                        </div>
                        {showTranslateText && (
                          <div
                            className="translate-content-modal"
                            onClick={() => {}}
                          >
                            <h1>
                              录音内容
                              <CloseOutlined onClick={toggleShowTranslate} />
                            </h1>
                            <div>{renderTranslate()}</div>
                          </div>
                        )}
                      </div>
                    )}
                    {recordStatus === recordStatusEnum.recording && (
                      <div className="pause" onClick={pauseRecord}>
                        <img src={pause} alt="" />
                      </div>
                    )}
                    {recordStatus === recordStatusEnum.pause && (
                      <div className="play" onClick={continueRecord}>
                        <img src={play} alt="" />
                      </div>
                    )}

                    {recordStatus !== recordStatusEnum.init &&
                      recordStatus !== recordStatusEnum.end && (
                        <div className="stop" onClick={endRecord}>
                          <div></div>
                        </div>
                      )}
                    {recordStatus === recordStatusEnum.end && (
                      <div className="generate">
                        <div
                          className={
                            generating
                              ? "button-content disabled"
                              : "button-content"
                          }
                          onClick={generate}
                        >
                          {generating
                            ? [
                                <LoadingOutlined className="generate-loading" />,
                                "会议纪要生成中",
                              ]
                            : "AI生成会议纪要"}
                        </div>
                        <div className="meeting-type">
                          <div className="choose" onClick={toggleShowOptions}>
                            <span className="text">
                              {chooseTemplate?.label || "请选择"}
                            </span>
                            {showOptions ? <DownOutlined /> : <UpOutlined />}
                          </div>
                          {showOptions
                            ? OPTIONS_TEMPLATE.map((e) => {
                                return (
                                  <div
                                    key={e.value}
                                    className="option-item"
                                    onClick={() => setChooseTemplateFunc(e)}
                                  >
                                    {e.label}
                                  </div>
                                );
                              })
                            : null}
                        </div>
                      </div>
                    )}
                  </>
                )}

                {meeting_type === "1" && (
                  <>
                    {/* {recordStatus === recordStatusEnum.init && (
                      <div
                        className="start-record"
                        onClick={startRecording}
                      ></div>
                    )} */}
                    {recordStatus !== recordStatusEnum.init && (
                      <div
                        className={
                          recordStatus === recordStatusEnum.recording
                            ? "record-detail record-detail-recording"
                            : "record-detail"
                        }
                      >
                        <div
                          className="record-detail-button"
                          onClick={toggleShowTranslate}
                        >
                          <span>
                            {recordStatus === recordStatusEnum.recording
                              ? [
                                  <AudioOutlined className="record_icon" />,
                                  "录音中...",
                                ]
                              : "音频内容"}
                          </span>
                          {showTranslateText ? (
                            <DownOutlined />
                          ) : (
                            <UpOutlined />
                          )}
                        </div>
                        {showTranslateText && (
                          <div
                            className="translate-content-modal"
                            onClick={() => {}}
                          >
                            <h1>
                              录音内容
                              <CloseOutlined onClick={toggleShowTranslate} />
                            </h1>
                            <div>{renderTranslate()}</div>
                          </div>
                        )}
                      </div>
                    )}
                    {recordStatus === recordStatusEnum.end && (
                      <div className="generate">
                        <div
                          className={
                            generating
                              ? "button-content disabled"
                              : "button-content"
                          }
                          onClick={generate}
                        >
                          {generating
                            ? [
                                <LoadingOutlined className="generate-loading" />,
                                "会议纪要生成中",
                              ]
                            : "AI生成会议纪要"}
                        </div>
                        <div className="meeting-type">
                          <div className="choose" onClick={toggleShowOptions}>
                            <span className="text">
                              {chooseTemplate?.label || "请选择"}
                            </span>
                            {showOptions ? <DownOutlined /> : <UpOutlined />}
                          </div>
                          {showOptions
                            ? OPTIONS_TEMPLATE.map((e) => {
                                return (
                                  <div
                                    key={e.value}
                                    className="option-item"
                                    onClick={() => setChooseTemplateFunc(e)}
                                  >
                                    {e.label}
                                  </div>
                                );
                              })
                            : null}
                        </div>
                      </div>
                    )}
                  </>
                )}
              </div>
            )}
          </div>
          <div className="content-right"></div>
        </div>
      </Spin>
    </div>
  );
}

// http://localhost:5174/#/main/createMeetingMinutes?meeting_id=c0d2040b-2c92-4f31-a4d8-1fb913063814&customer=%E5%AE%A2%E6%88%B7%E5%B0%8F%E5%88%98&title=%E8%BF%99%E6%98%AF%E4%B8%80%E4%B8%AA%E5%9C%A8%E7%BA%BF%E4%BC%9A%E8%AE%AE%E7%BA%AA%E8%A6%81&template_id=42b36afd-6940-4415-9097-97ff34544d64&meeting_type=1&pageStatus=edit&meetingNum=87662210137&meetingPwd=C76eWa&meetingName=%E8%B5%B5%E5%B0%8F%E5%B0%8F2
